package com.example.banksystem.service;


import com.example.banksystem.entity.Account;
import com.example.banksystem.entity.Transaction;
import com.example.banksystem.entity.User;
import com.example.banksystem.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Service
public class WithdrawService {

    @Autowired
    private AccountRepository accountRepository;

    @Autowired
    private TransactionServer transactionServer;

    /**
     * 取款操作
     * @param user 用户
     * @param amount 取款金额
     * @return 操作结果
     */
    @Transactional
    public String withdraw(User user, BigDecimal amount) {
        // 1. 验证金额合法性
        if (amount.compareTo(BigDecimal.ZERO) <= 0) {
            return "取款金额必须大于0";
        }

        // 2. 查询用户账户
        Account account = accountRepository.findByUser(user)
                .orElseThrow(() -> new RuntimeException("用户账户不存在"));

        // 3. 验证账户状态
        if (!"ACTIVE".equals(account.getStatus())) {
            return "账户状态异常，无法取款";
        }

        // 4. 验证余额是否充足
        if (account.getBalance().compareTo(amount) < 0) {
            return "余额不足，无法取款";
        }

        // 5. 执行取款操作（扣减余额）
        account.setBalance(account.getBalance().subtract(amount));
        accountRepository.save(account);

        // 6. 记录交易记录
        Transaction transaction = new Transaction();
        transaction.setUser(user);
        transaction.setAmount(amount);
        transaction.setType("WITHDRAW"); // 取款类型
        transaction.setTime(LocalDateTime.now());
        transaction.setStatus("SUCCESS");
        transactionServer.saveTransaction(transaction);

        return "取款成功，当前余额：" + account.getBalance();
    }
}
